# -*- coding: utf-8 -*-
# @Time    : 2018-05-30 10:10
# @Author  : Yang Feng
# @Email   : yangfeng@bbdservice.com
# @File    : Rule30_LoanCard_InspectCnt_6monCheck.py
# @Software: PyCharm


'''eof
name:近半年贷款审批机构数和信用卡审批查询次数校验
code:LoanAndCard_InspectCnt_6monCheck
tableName:
columnName:
groups:准入>个人征信
dependencies:IC
type:常用指标
datasourceType:在线指标
description:
eof'''

import sys
import json
import pandas as pd
import datetime
import traceback
reload(sys)
sys.setdefaultencoding('utf-8')

null_type_list = ['', None, 'null', '/', 'Null']


def FormatData(tableName):
    try:
        icr = json.loads(IC[0]["icr"])[tableName]
        return icr if isinstance(icr, list) and len(icr) > 0 else [{}]
    except:
        print traceback.format_exc()
        return [{}]


def Formate(time):
    import re
    import datetime
    r = re.compile(r'\D+')
    try:
        date = datetime.datetime.strptime(time, '%Y.%m.%d').strftime('%Y%m%d')
    except:
        try:
            date = datetime.datetime.strptime(time, '%Y-%m-%d').strftime('%Y%m%d')
        except:
            try:
                date = datetime.datetime.strptime(time, '%Y/%m/%d').strftime('%Y%m%d')
            except:
                try:
                    tmp = r.sub('', time)
                    date = datetime.datetime.strptime(tmp, '%Y%m%d').strftime('%Y%m%d')
                except:
                    date = None
    return date




def LoanAndCard_InspectCnt_6mon():
    try:
        last_year_list = [(datetime.datetime.now() - pd.tseries.offsets.DateOffset(months=i)).strftime('%Y%m%d') \
                          for i in [6, 0]]
        icrRecordDetailList = FormatData("ICRRecordDetail")
        if icrRecordDetailList == [{}]:
            return u'缺失值'
        else:
            returnList1 = []
            returnList2 = []
            returndate1=[]
            returndate2=[]
            for icrLoanInfo002Loan in icrRecordDetailList:
                try:
                    # 查询时间
                    queryDate = icrLoanInfo002Loan.get('QueryDate')
                    # 查询原因
                    queryReason = icrLoanInfo002Loan.get('QueryReason')
                    #查询操作员
                    Querier = icrLoanInfo002Loan.get('Querier')
                    queryDateFormat = Formate(queryDate)
                    if queryDateFormat is None or queryReason in null_type_list:
                        returnList1.append(None)
                        returnList2.append(None)
                        continue
                    if  queryDateFormat>last_year_list[0] and queryDateFormat<=last_year_list[1]  \
                            and (u"贷款" in queryReason):
                        returnList1.append(Querier)
                        returndate1.append(queryDateFormat)
                        continue
                    if queryDateFormat>last_year_list[0] and queryDateFormat<=last_year_list[1]  \
                            and (u"贷记卡" in queryReason or u"信用卡" in queryReason):
                        returnList2.append(Querier)
                        returndate2.append(queryDateFormat)
                        continue
                    else:
                        returnList1.append(0)
                        returnList2.append(0)
                except:
                    returnList1.append(None)
                    returnList2.append(None)
                    continue
            returnSet1 = set(returnList1)
            returnSet2 = set(returnList2)
            returnSet=list(returnSet1)+list(returnSet2)
            returnListNotNone = filter(lambda x:x is not None, returnSet)
            returnListNotZero = filter(lambda x:x != 0, returnListNotNone)

            if len(returnListNotNone) == 0:
                return u"缺失值"
            elif len(returnListNotZero) == 0:
                return 0
            else:
                return len(returnListNotZero)
    except:
        return u"缺失值"

result = LoanAndCard_InspectCnt_6mon()